<?php

namespace app\api\controller\log;
use app\api\controller\common\ApiBase;
use Think\Db;
class Companylog extends ApiBase
{

    public function index()
    {
        if (request()->isPost()) {
            $page = $this->request->param('page');
            $keyword = $this->request->param('keyword');
            $exhibition_id = $this->request->param('exhibition_id');
            $companyName = $this->request->param('companyName');
            $page = max(1, intval($page));
            $pagesize = $this->request->param('pageSize')?$this->request->param('pageSize'):10;
            $param=" and p.exhibition_id=$exhibition_id ";
            if(empty($exhibition_id)){
                return json(['code'=>0,'msg'=>'缺少关键主键展会id']);
            }
            if (!empty($keyword)) {
                $param.=" and p.operator_id in (select id from crm_admin where realname like '%$keyword%') ";
            }
            $tabName=$this->getTabName($exhibition_id);
            $tabName='crm_'.$tabName;
            if(!empty($companyName)){
                $param.=" and p.company_id in (select id from ".$tabName." where company_name like '%$companyName%') ";
            }
            $sql2="select p.*,z.company_name,a.realname,c.realname as c_realname";
            $sql2.=" from crm_company_log as p ";
            $sql2.=" left join ".$tabName." as z on z.id=p.company_id";
            $sql2.=" left join crm_admin as a on a.id=p.operator_id";
            $sql2.=" left join crm_admin as c on c.id=p.receiver_id";
            $sql2.=" where 1=1 $param";
            $sql2.=" order by p.id desc";
            $sql2.=" limit ".($page-1)*$pagesize.",$pagesize";
            $list=Db::query($sql2);
            $sql21=" select count(p.id) as count1 ";
            $sql21.=" from crm_company_log as p ";
            $sql21.=" where 1=1 $param";
            $total1=Db::query($sql21);
            $total=$total1[0]['count1']; //st
            foreach ($list as &$v){
                $v['realname']=$v['c_realname']?$v['c_realname']:$v['realname'];
            }
            return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'total'=>$total]]);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }
    public function getTabName($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName="";
        if($result){
            $tabName=$result['create_tablename'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
    }

}
